package com.yanzhen.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageInfo;
import com.yanzhen.common.annotation.SysLog;
import com.yanzhen.model.TypeInfo;
import com.yanzhen.service.ITypeInfoService;
import com.yanzhen.util.ExcelUtil;
import com.yanzhen.util.JsonObject;
import com.yanzhen.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.print.Book;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 社团分类和介绍 前端控制器
 * </p>
 *
 * @author kappy
 * @since 2022-07-25
 */
@Data
@Api(tags = {"社团分类和介绍"})
@RestController
@RequestMapping("/typeInfo")
public class TypeInfoController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private ITypeInfoService typeInfoService;

    /**
      分页高级查询
     */
    @RequestMapping("/queryTypeList")
    public JsonObject queryTypeList(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "15") Integer limit,
                                    String name){

      //创建对象模型
      JsonObject object=new JsonObject();
      //包装对象
        TypeInfo info=new TypeInfo();
        info.setName(name) ;
      //获取结果集合
      PageInfo<TypeInfo> pageInfo = typeInfoService.queryTypeList(page, limit, info);
      object.setCode(20000);
      object.setTotal(pageInfo.getTotal());
      object.setData(pageInfo.getList());
      return object;
    }


    @ApiOperation(value = "新增社团分类和介绍")
    @SysLog("新增社团类型")
    @RequestMapping("/addInfo")
    public R add(@RequestBody TypeInfo typeInfo){
        //新增后的返回参数  如果是1 成功 0 失败
        int num= typeInfoService.add(typeInfo);
        if(num>0){
            return R.ok();
        }
        return R.fail("类型添加失败");
    }

    @ApiOperation(value = "删除社团分类和介绍")
    @SysLog("删除社团类型")
    @RequestMapping("/deleteById")
    public R delete(Long id){
        int num= typeInfoService.delete(id);
        if(num>0){
            return R.ok();
        }
        return R.fail("删除失败");
    }

    @ApiOperation(value = "更新社团分类和介绍")
    @SysLog("更新社团类型")
    @RequestMapping("/updateInfo")
    public R update(@RequestBody TypeInfo typeInfo){
        int num= typeInfoService.updateData(typeInfo);
        if(num>0){
            return R.ok();
        }
        return R.fail("修改失败");
    }

    @ApiOperation(value = "查询社团分类和介绍分页数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "页码"),
        @ApiImplicitParam(name = "pageCount", value = "每页条数")
    })
    @GetMapping()
    public IPage<TypeInfo> findListByPage(@RequestParam Integer page,
                                          @RequestParam Integer pageCount){
        return typeInfoService.findListByPage(page, pageCount);
    }

    @ApiOperation(value = "id查询社团分类和介绍")
    @GetMapping("{id}")
    public TypeInfo findById(@PathVariable Long id){
        return typeInfoService.findById(id);
    }

    @ApiOperation(value = "导出Excel测试")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<TypeInfo> list = typeInfoService.getBaseMapper().selectList(null);
        System.out.println(list);
       /* //excel文件名
        final String FILENAME = "类型信息";
        //sheetName
        final String SHEETNAME = "社团类型信息表";
        //获取model对象类
        Class typeInfo = TypeInfo.class;

        try {
            //表头样式策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            //初始化表格样式
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

                response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(FILENAME, "UTF-8").replaceAll("\\+", "%20");
            //响应首部 Access-Control-Expose-Headers 就是控制“暴露”的开关，它列出了哪些首部可以作为响应的一部分暴露给外部。
            //此处设置了开放Content-Disposition，前端可获取该响应参数获取文件名称
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), typeInfo).autoCloseStream(Boolean.FALSE)
                    .registerWriteHandler(horizontalCellStyleStrategy).sheet(SHEETNAME).doWrite(list);

        } catch (IOException e) { //下载失败情况的处理
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }*/
       /* // 设置响应类型
        response.setContentType("application/vnd.ms-excel");
        // 设置响应头
        response.setHeader("Content-Disposition", "attachment; filename=" + "test.xlsx");
        ExcelUtil.writeExcel(response,list);*/

        //从HttpServletResponse中获取OutputStream输出流
        try {
            // 设置响应类型
            response.setContentType("application/vnd.ms-excel");
            // 设置编码格式
            response.setCharacterEncoding("utf-8");
            // 设置URLEncoder.encode 防止中文乱码
            String fileName = URLEncoder.encode("用户信息表", "UTF-8").replaceAll("\\+", "%20");
            // 设置响应头
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 写出Excel
            EasyExcel.write(response.getOutputStream(), TypeInfo.class).inMemory(true).sheet("用户信息表").doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException("数据或文件损坏，无法下载");
        }
    }

}
